package com.zhengbo.simplerpc.common;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ReplayingDecoder;

import java.util.List;

/**
 * Created by zhengbo on 2019/8/21.
 */
public class MessageDecoder extends ReplayingDecoder<MessageInput> {

    private String readStr(ByteBuf in) {

        int len = in.readInt();

        byte[] bytes = new byte[len];
        in.readBytes(bytes);
        return new String(bytes, Constants.DEFAULT_CHARSET);
    }

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {

        String requestId = readStr(in);
        String type = readStr(in);
        String content = readStr(in);

        out.add(new MessageInput(type, requestId, content));

    }
}
